import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessUserEntity } from '../entity/user';
import * as md5 from 'md5';
import * as _ from 'lodash';
import { CacheManager } from '@midwayjs/cache';
import { Context } from '@midwayjs/koa';

/**
 * 用户管理
 */
@Provide()
export class BusinessUserService extends BaseService {
  @InjectEntityModel(BusinessUserEntity)
  businessUserEntity: Repository<BusinessUserEntity>;

  @Inject()
  cacheManager: CacheManager;

  @Inject()
  ctx: Context;

  /**
   * 分页查询
   * @param query
   */
  async page(query: any, option: any, connectionName?: any) {
    const result = await super.page(query, option, connectionName);
    result.list = result.list.map(item => {
      delete item.password;
      return item;
    });
    return result;
  }

  /**
   * 新增
   * @param param
   */
  async add(param) {
    const exists = await this.businessUserEntity.findOneBy({
      username: param.username,
    });
    if (!_.isEmpty(exists)) {
      throw new CoolCommException('用户名已经存在~');
    }
    param.password = md5(param.password);
    await this.businessUserEntity.save(param);
    return {
      id: param.id,
    };
  }

  /**
   * 根据ID获得信息
   * @param id
   */
  public async info(id) {
    const info = await this.businessUserEntity.findOneBy({ id });
    if (info) {
      delete info.password;
    }
    return info;
  }

  /**
   * 根据ID获得信息
   * @param id
   */
  public async getUserinfoByClient() {
    const { userId } = this.ctx.admin;
    const info = await this.businessUserEntity.findOneBy({ id:userId });
    if (info) {
      delete info.password;
    }
    return info;
  }

  /**
   * 修改
   * @param param 数据
   */
  async update(param) {
    if (!_.isEmpty(param.password)) {
      param.password = md5(param.password);
      const userInfo = await this.businessUserEntity.findOneBy({
        id: param.id,
      });
      if (!userInfo) {
        throw new CoolCommException('用户不存在');
      }
      param.passwordV = userInfo.passwordV + 1;
      await this.cacheManager.set(
        `business:passwordVersion:${param.id}`,
        param.passwordV
      );
    } else {
      delete param.password;
    }
    if (param.status === 0) {
      await this.forbidden(param.id);
    }
    await this.businessUserEntity.save(param);
  }
  /**
   * 禁用用户
   * @param userId
   */
  async forbidden(userId) {
    await this.cacheManager.del(`business:token:${userId}`);
  }
}
